import java.util.Arrays;

public class Test4 {
    /**
     * 归并排序：
     * 时间复杂度：O(N*logN)
     * 空间复杂度：O(N)
     * 稳定性：稳定的排序
     * 如果 array[s1] <= array[s2] 不取等号  那么就是不稳定的排序
     *
     * 学过的排序 只有3个是稳定的：
     * 冒泡   插入   归并
     * @param array
     */
    public static void mergeSort1(int[] array) {
        mergeSortInternal(array,0,array.length-1);
    }

    private static int[] mergeSortInternal(int[] array, int low, int high) {
        if(low>=high) {
            return array;
        }

        //int mid = (low+high) >>> 1;
        int mid = low + ((high-low) >>> 1);
        //左边
        mergeSortInternal(array,low,mid);
        //右边
        mergeSortInternal(array,mid+1,high);
        //合并
        merge(array,low,mid,high);
        return array;
    }

    private static void merge(int[] array,int low,int mid,int high) {
        int[] tmp = new int[high-low+1];
        int k = 0;//

        int s1 = low;
        int e1 = mid;
        int s2 = mid+1;
        int e2 =  high;

        while (s1 <= e1 && s2 <= e2) {
            if(array[s1] <= array[s2]) {
                tmp[k++] = array[s1++];
            }else {
                tmp[k++] = array[s2++];
            }
        }

        while (s1 <= e1) {
            tmp[k++] = array[s1++];
        }

        while (s2 <= e2) {
            tmp[k++] = array[s2++];
        }
        //拷贝tmp数组的元素 放入原来的数组array当中
        for (int i = 0; i < k; i++) {
            array[i+low] = tmp[i];
        }
    }
    /**
     * 非递归实现归并排序
     *
     * @param array
     */
    public static void mergeSort(int[] array) {
        int nums = 1;//每组的数据个数
        while (nums < array.length) {
            //数组每次都要进行遍历,确定要归并的区间
            for (int i = 0; i < array.length; i += nums*2) {
                int left = i;
                int mid = left+nums-1;
                //防止越界
                if(mid >= array.length) {
                    mid = array.length-1;
                }
                int right = mid+nums;
                //防止越界
                if(right >= array.length) {
                    right = array.length-1;
                }
                //小标确定之后，进行合并
                merge(array,left,mid,right);
            }
            nums *= 2;
        }
    }

    public static void main(String[] args) {
        int[] array = {2,45,23,67,34,3,56};
        int[] ret = mergeSortInternal(array,0,array.length-1);
        System.out.println(Arrays.toString(ret));
    }
}
